<?php

namespace app\model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * 创建分表逻辑
 */
trait SplitTableTrait
{
    protected function getSuffixBySplitType()
    {
        $suffix = '';
        switch ($this->splitType) {
            case 'Ym':
                $suffix = date('Ym');
                break;
            case 'oW':
                $suffix = date('oW');
                break;
            case 'w':
                $suffix = date('w');
                break;
        }

        return $suffix;
    }

    protected function setSuffix($suffix)
    {
        $this->suffix = $suffix;
    }

    public function getSuffix()
    {
        return $this->suffix;
    }

    public function getSuffixByTableName()
    {
        $table = $this->getTable();
        $suffix = str_replace("{$this->originTable}_", '', $table);

        return $suffix;
    }

    protected function updateTableName()
    {
        $split_table = "{$this->originTable}_{$this->suffix}";
        $this->table = $split_table;
    }

    /**
     * 在模型实例化后调用此接口，用于判断是否需要创建分表，如果创建了分包则将表名改成分表表名
     *
     * @return void
     */
    protected function initSplitTable($create_split = false)
    {
        // 原始表名
        if (empty($this->originTable)) {
            $this->originTable = $this->table;
        }
        $origin_table = $this->originTable;

        // 分表后缀
        if ($this->suffix == '') {
            $suffix = $this->getSuffixBySplitType();
            if ($suffix == '') {
                return;
            }
            $this->setSuffix($suffix);
        }
        $suffix = $this->suffix;

        $split_table = "{$origin_table}_{$suffix}";
        if ($create_split && !Schema::connection($this->connection)->hasTable($split_table)) {
            DB::connection($this->connection)->update("create table {$split_table} like {$origin_table}");
        }

        //最终表替换模型中声明的表作为分表使用的表
        $this->updateTableName();
    }

    /**
     * 提供一个静态方法设置表后缀，并动态创建此后缀不存在的分包
     *
     * @param string $suffix
     *
     * @return Illuminate\Database\Eloquent\Model
     */
    public static function suffix($suffix, $create_split = false)
    {
        $instance = new static;
        $instance->setSuffix($suffix);
        $instance->updateTableName();
        $instance->initSplitTable($create_split);
        return $instance;
    }
}
